import React, { useEffect, useState } from "react";
import { View, Text, StyleSheet, FlatList } from "react-native";
import Dropdown from "../../components/dropdown";
import NoData from "../../components/preAdmin/NoData";
import query from "../../api/query";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useSelector } from "react-redux";
import LoadingBar from "../../components/InterView/LoadingBar";
const ScoreManage = () => {
  const user = useSelector((state) => state.authR.user);
  const [groups, setGroups] = useState([]);
  const [tests, setTests] = useState([]);
  const [groupId, setGroupId] = useState(0);
  const [testId, setTestId] = useState(0);
  const [scoreList, setScoreList] = useState([]); //原始数据
  const [filterList, setFilterList] = useState([]); //过滤数据
  const [isGroupVisible, setIsGroupVisible] = useState(true);

  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setIsLoading(true);
        //成绩
        const token = await AsyncStorage.getItem("token");

        if (user.role === "admin") {
          console.log("jinlail");
          const result = await query.get("/score/group/", {
            headers: { Authorization: token },
          });
          setScoreList(result.data.data);
          setFilterList(result.data.data);
        } else {
          const result = await query.get("/score", {
            headers: { Authorization: token },
          });
          setScoreList(result.data.data);
          setFilterList(result.data.data);
        }
        // console.log("成绩", result.data.data);

        //试卷
        const title = await query.get("/test/published", {
          headers: { Authorization: token },
        });
        let titleList = ["全部"];
        title.data.data.map((item) => titleList.push(item.title));
        setTests(titleList);

        //组别
        const group = await query.get("/user/group", {
          headers: { Authorization: token },
        });
        group.data.data.unshift("全部");
        setGroups(group.data.data);

        if (user.role === "admin") {
          let groupNum = group.data.data.indexOf(user.group);
          setGroupId(groupNum);
          setIsGroupVisible(false);
        }
      } catch (err) {
        console.log("初始化成绩出错", err);
      }
      setIsLoading(false);
    };
    fetchData();
  }, []);

  const onFilter = (group, test) => {
    let filtered = [];
    if (group === 0 && test === 0) {
      filtered = scoreList;
    } else if (group === 0) {
      filtered = scoreList.filter((item) => item.testId.title === tests[test]);
    } else if (test === 0) {
      filtered = scoreList.filter(
        (item) => item.userId.group === groups[group]
      );
    } else {
      filtered = scoreList.filter(
        (item) =>
          item.testId.title === tests[test] &&
          item.userId.group === groups[group]
      );
    }

    setFilterList(filtered);
  };

  return (
    <View style={styles.container}>
      <LoadingBar visible={isLoading} />
      <View style={styles.top}>
        {isGroupVisible && (
          <View style={styles.addItem}>
            <Text style={{ fontSize: 16, marginBottom: 2 }}>组别:</Text>
            <Dropdown
              ifFirst={1}
              initialValues={{
                initKey: groupId,
                initOptions: groups,
              }}
              initialStyles={{
                valueWith: 80,
                valueMarginTop: 0,
                optionsWidth: 110,
                optionsBackGroundColor: "#eee",
                optionsBorderColor: "#ccc",
              }}
              onSelect={(item, value) => {
                setGroupId(value);
                onFilter(value, testId);
              }}
            />
          </View>
        )}

        <View style={styles.addItem}>
          <Text style={{ fontSize: 16, marginBottom: 2 }}>试卷:</Text>
          <Dropdown
            ifFirst={1}
            initialValues={{
              initKey: testId,
              initOptions: tests,
            }}
            initialStyles={{
              valueWith: 80,
              valueMarginTop: 0,
              optionsWidth: 110,
              optionsBackGroundColor: "#eee",
              optionsBorderColor: "#ccc",
            }}
            onSelect={(item, value) => {
              setTestId(value);
              onFilter(groupId, value);
            }}
          />
        </View>
      </View>
      <FlatList
        ListEmptyComponent={<NoData />}
        keyExtractor={(item, index) => index.toString()}
        data={filterList}
        ItemSeparatorComponent={() => (
          <View style={styles.itemSeparator}></View>
        )}
        renderItem={({ item, index }) => {
          return (
            <View
              style={{
                flexDirection: "row",
                padding: 16,

                paddingHorizontal: 10,
              }}
            >
              <Text style={styles.form}>{item.userId.name}</Text>
              <Text style={styles.form}>{item.userId.group}</Text>
              <Text style={styles.form}>{item.testId.title}</Text>
              <View style={styles.form}>
                <Text style={styles.finishText}>{item.score}</Text>
              </View>
            </View>
          );
        }}
      />
    </View>
  );
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "white",
  },
  top: {
    flexDirection: "row",
    // justifyContent: "space-around",
    justifyContent: "space-between",
    borderBottomWidth: 2,
    borderBottomColor: "#eee",
  },
  addItem: {
    flexDirection: "row",
    padding: 15,
    alignItems: "center",
    justifyContent: "center",
  },
  title: {
    fontSize: 16,
    color: "#22254c",
  },
  itemSeparator: {
    width: "90%",
    height: 1,
    backgroundColor: "#eee",
    alignSelf: "center",
  },
  form: {
    flex: 1,
    textAlign: "center",
    alignSelf: "center",
  },
  finishText: {
    color: "#A9D67C",
    textAlign: "center",
    fontWeight: "bold",
  },
  unfinishText: {
    color: "#F47C68",
    textAlign: "center",
    fontWeight: "bold",
  },
});

export default ScoreManage;
